// pages/detail/detail.js
import { shareOptions } from '../../utils/access';
import request from '../../utils/request'
import { stringify, getStorage, setStorage } from '../../utils/utils';
const api = require("../../config/api");
const wxParse = require('../../utils/wxParse/wxParse.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showTopBtn:false,
    modalButtons: [
      {
        text: "取消",
        extClass: "modalCloseButton",
      },
      {
        text: "确定",
        extClass: "modalButton",
      },
    ],
    modal: {
      show: false,
      title: "开始答题挑战",
      content: "您还有X篇知识未学习\n确定现在开始答题挑战吗？",
    },
    taskId: null,
    knowledgeId: null,
    knowledgeName: null,
    isTask: true,
    showNext: true,
    tip: '',
    id: '',
    modalShow: false,
    question: null,
    detail: {},
    // 头像
    avatar: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const userInfo = getStorage('userInfo')
    this.setData({
      id: options?.id,
      avatar: userInfo.avatarUrl,
      taskId: options?.taskId,
    })
    // this.getData(options?.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    wx.getSystemInfo({
      success: (result) => {
        that.setData({
          screenH:result.screenHeight
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.id){
      console.log("hhhhhhh==",this.data.id);
      this.getData(this.data.id)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 增加阅读数
   */
  async addRead(id = '') {
    await request.get(`${api.addRead}/${id}`,{},{loading:false})
  },

  /**
   * 获取数据
   * @param {*} id 
   */
  async getData(id = '') {
    let { showNext } = this.data
    const res = await request.get(`${api.knowledgeDetail}/${id}`,{},{loading:false})
    const content = decodeURIComponent(res.data.content)
    wxParse.wxParse('contentData', 'html', content, this)
    
    //判断文章状态
    // const statusRes = await request.get(`${api.getArticleStatus}/${id}`,{},{loading:false})
    const statusRes = await request.get(`${api.getArticleStatus}/${id}`)
    console.log('statusRes', statusRes);
    
    const isTask = statusRes?.data?.isTask == 1
    await this.addRead(id)

    //获取底部提示
    let hasStudy = getStorage('study')
    if (hasStudy.search(res.data.id) == -1) {
      hasStudy += res.data.id + ','
      setStorage('study', hasStudy)
    }
    const tipResult = await request.get(api.getReadTips,{},{loading:false})
    const tipRes = tipResult?.data || {}
    let tip = ''
    if (tipRes.readNumber < tipRes.total) {
      tip = "加油！当前共有" + tipRes.total + "篇知识，您已学习了" + tipRes.readNumber + "篇"
      showNext = true
    } else {
      tip = "太棒了！当前共有" + tipRes.total + "篇知识需要学习，您已全部浏览！"
      showNext = false
    }

    console.log(tipRes.total - tipRes.readNumber);
    this.setData({
      detail: res?.data || {},
      knowledgeId: res?.data?.knowledgeId,
      knowledgeName: res?.data?.knowledgeName,
      question: res?.data?.questionData,
      isTask,
      taskId: statusRes?.data?.taskId,
      showNext: isTask && showNext,
      tip,
      total: tipRes.total,
      readNumber: tipRes.readNumber,
      surplus: tipRes.total - tipRes.readNumber,
    })
    wx.stopPullDownRefresh()
  },

  //获取底部提示
  async getBottomTip() {
    let { showNext } = this.data
    //获取底部提示
    const study = getStorage('study')
    let number = study.split(',').length - 1
    const tipResult = await request.get(api.getReadTips,{},{loading:false})
    const tipRes = tipResult?.data || {}
    let tip = ''
    if (tipRes.readNumber < tipRes.total) {
      tip = "加油！当前共有" + tipRes.total + "篇知识，您已学习了" + tipRes.readNumber + "篇"
      showNext = true
    } else {
      tip = "太棒了！当前共有" + tipRes.total + "篇知识需要学习，您已全部浏览！"
      showNext = false
    }
    this.setData({
      showNext,
      total: tipRes.total,
      readNumber: tipRes.readNumber,
      surplus: tipRes.total - tipRes.readNumber,
      tip
    })
  },

  //跳转文章列表
  toArticleList() {
    const pages = getCurrentPages()
    const last = pages[pages.length - 2]
    if (last?.route === 'pages/list/list') {
      wx.navigateBack({
        delta: 1,
      })
    } else {
      wx.redirectTo({
        url: `/pages/list/list?id=${this.data.knowledgeId}&title=${this.data.knowledgeName}`,
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getData(this.data.id)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 去答题
  toAnswer() {
    let { question, isTask, taskId, detail, modal, surplus } = this.data
    detail.content = decodeURIComponent(detail.content)?.replace(/<[^>]+>/gim, '').trim().substr(0, 100)
    if (isTask) {
      // if (surplus > 0) {
      //   this.setData({
      //     modal: {
      //       ...modal,
      //       show: true,
      //       content: `您还有${surplus}篇知识未学习\n确定现在开始答题挑战吗？`
      //     }
      //   })
      // } else {
        wx.navigateTo({
          url: `/pages/answer/answer?taskId=${taskId}&detail=${stringify(detail)}`,
        })
      // }
    } else {
      wx.navigateTo({
        url: `/pages/answer/answer?question=${stringify(question)}&detail=${stringify(detail)}`,
      })
    }
  },
  //继续学习
  async showNextArticle(e) {
    console.log('e', e);
    let type = e.currentTarget.dataset.type
    const { id, taskId, isTask } = this.data
    let params = {
      knowledgeInfoId: id,
      taskId: taskId ? taskId : 0,
      type
    }

    const res = await request.get(`${api.getNext}`, params)
    console.log('nextres', res);
    if (res.data !== null) {
      const content = decodeURIComponent(res.data.content)
      wxParse.wxParse('contentData', 'html', content, this)
      console.log('res.data', res.data);

      let hasStudy = getStorage('study')
      if (hasStudy.search(res.data.id) == -1) {
        hasStudy += res.data.id + ','
        setStorage('study', hasStudy)
      }

      await this.addRead(res.data.id)

      this.getBottomTip()

      //判断文章状态
      const statusRes = await request.get(`${api.getArticleStatus}/${res?.data?.id}`,{},{loading:false})

      this.setData({
        id: res?.data?.id,
        detail: res?.data,
        knowledgeId: res?.data?.knowledgeId,
        knowledgeName: res?.data?.knowledgeName,
        question: res?.data?.questionData,
        isTask: statusRes?.data?.isTask == 1,
        taskId: statusRes?.data?.taskId,
      })
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      let title = type == 2 ? '这是第一篇~' : '最后一篇了~'
      wx.showToast({
        title,
        icon: 'none'
      })
    }
  },
  // 隐藏弹窗
  hideModal() {
    this.setData({
      modalShow: false
    })
  },
  // 弹窗按钮点击
  clickDialogBtn(e) {
    const { taskId, detail, modal } = this.data
    if (e.detail.index) {
      this.setData({
        modal: {
          ...modal,
          show: false
        }
      })
      wx.navigateTo({
        url: `/pages/answer/answer?taskId=${taskId}&detail=${stringify(detail)}`,
      })
    } else {
      this.setData({
        modal: {
          ...modal,
          show: false
        }
      })
    }
  },
  // 用户点击右上角分享
	onShareAppMessage(e) {
		return shareOptions('default', e)
  },
  // 滚动到顶部
  toTop(){
    wx.pageScrollTo({
      scrollTop:0,
      duration: 300,
    })
    this.setData({
      showTopBtn:false
    })
  },
  onPageScroll(e){
    let { screenH,showTopBtn } = this.data
    this.setData({
      showTopBtn:e.scrollTop>(screenH/2)
    })
  },
})